#!/bin/sh

. scripts/functions

#
# Test the truncate command
#

get_filesize()
{
    stat --printf="%s" "$1"
}

# Define the Name of the test as "TestName".
# Should be the same as the filename, therefore we use the filename as default.
TestName="`basename $0`"

# set other test specific variables
Client=susan-fd
JobName=backup-susan-fd

# a truncated volume has not the size 0, but is at least smaller than this (default block size)
MinVolumeSize=65536
VolumeName=TestVolume001

# Remove old configuration, working and tmp files. Setup the database.
cleanup

# Config files will be copied to required location.
# Base configuration files come from the
# configs/BASE/ directory, see
# configs/BASE/README.txt for an overview of the provides resources.
# Store your additonal resources to
# configs/$TestName.
# It is also possible to overwrite resources from configs/BASE.
# If you define a full config file (instead of config files for individual resources),
# only these will be taken.
copy_configs

# Directory to backup.
# This directory will be created by setup_data().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data data/small.tgz

# the default fileset FS_TESTJOB backups all file and directories defined in "${tmp}/file-list".
echo "${BackupDirectory}" >${tmp}/file-list


# start the test
start_test

# ${tmp}/bconcmds lists the bconsole commands executed by "run_susan"
# create a volume and put data on it.
cat <<END_OF_DATA >${tmp}/bconcmds
messages
@$out ${tmp}/log1.out w
label storage=File1 volume=${VolumeName} pool=Default
run job=$JobName storage=File1 yes
wait
messages
END_OF_DATA

# Start the susan daemons
# and run the bconsole commands from ${tmp}/bconcmds
run_susan

# get size of backup job
#sed -r -n -e 's/ *SD Bytes Written: *([0-9,]*) .*/\1/p' tmp/log1.out  | sed s/,//
VolumeSizeWithJob=`get_filesize ${tmp}/${VolumeName}`

# do some manual testing
if [ ${VolumeSizeWithJob} -lt ${MinVolumeSize} ]; then
    set_error "Volume size: ${VolumeSizeWithJob} < ${MinVolumeSize}. Something went wrong with the backup."
fi


cat <<END_OF_DATA >${tmp}/bconcmds2
@$out ${tmp}/log2.out w
purge volume=${VolumeName}
truncate volstatus=Purged volume=${VolumeName} yes
messages
END_OF_DATA

run_bconsole ${tmp}/bconcmds2

# verify that all are terminated
check_for_zombie_jobs storage=File1 client=${Client}

# stop susan
stop_susan

# check tmp/log1.out and tmp/log2.out for errors
check_two_logs

VolumeSizeAfterTruncate=`get_filesize ${tmp}/${VolumeName}`

# do some manual testing
if [ ${VolumeSizeAfterTruncate} -gt ${MinVolumeSize} ]; then
    set_error "Volume size: ${VolumeSizeAfterTruncate} > ${MinVolumeSize}. Something went wrong with the truncate command."
fi

printf "Volume path:          %s\n" ${tmp}/${VolumeName}
printf "Size before truncate: %d\n" ${VolumeSizeWithJob}
printf "Size after truncate:  %d\n" ${VolumeSizeAfterTruncate}

# end tests and check for error codes
end_test
